<template>
  <div class="sms-contact-container">
    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧：客户分组树 -->
      <el-col :xs="24" :sm="24" :md="6" :lg="6" class="group-tree-col">
        <el-card shadow="hover" class="group-tree-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-folder-opened"></i>
              <span>客户分组</span>
            </div>
            <div class="header-actions">
              <el-button type="text" class="add-group-btn" @click="handleAddGroup">
                <i class="el-icon-plus"></i> 新建分组
              </el-button>
            </div>
          </div>

          <!-- 分组搜索 -->
<!--          <div class="group-search">-->
<!--            <el-input-->
<!--              v-model="groupSearchText"-->
<!--              placeholder="搜索分组"-->
<!--              prefix-icon="el-icon-search"-->
<!--              size="small"-->
<!--              clearable-->
<!--            ></el-input>-->
<!--          </div>-->

          <el-tree :data="groupTreeData" :props="defaultProps" :expand-on-click-node="false"
                   ref="tree" node-key="groupId" default-expand-all highlight-current
                   @node-click="handleNodeClick">
            <span class="custom-tree-node" slot-scope="{node,data}">
              <span class="node-label">
                <i v-if="data.groupId == 0" class="el-icon-s-home tree-icon" />
                <i v-else class="el-icon-document tree-icon" />
                {{ data.groupName }}
              </span>
              <span class="node-actions">
                <i class="el-icon-plus action-icon" title="增加" @click.stop="handleAddGroup(data)" v-if="data.groupId == 0"></i>
                <i class="el-icon-edit action-icon" title="编辑" @click.stop="handleGroupUpdate(data)" v-if="data.groupId != 0"></i>
                <i class="el-icon-delete action-icon" title="删除" @click.stop="handleGroupDelete(node, data)" v-if="data.groupId != 0"></i>
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧：客户列表 -->
      <el-col :xs="24" :sm="24" :md="18" :lg="18" class="customer-list-col">
        <el-card shadow="hover" class="customer-list-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-user"></i>
              <span>{{ currentGroupName }}</span>
            </div>
          </div>

          <!-- 搜索和筛选工具栏 -->
          <div class="search-toolbar">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
              <el-form-item prop="customerName">
                <el-input
                  v-model="queryParams.customerName"
                  placeholder="请输入客户姓名"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item prop="phoneNumber">
                <el-input
                  v-model="queryParams.phoneNumber"
                  placeholder="请输入手机号"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAddCustomer"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImportCustomer"
              >导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
              >导出</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleBatchDelete"
              >删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getCustomerList"></right-toolbar>
          </el-row>

          <!-- 客户表格 -->
          <div class="table-container">
            <el-table
              v-loading="loading"
              :data="customerList"
              @selection-change="handleSelectionChange"
            >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="客户姓名" prop="customerName" min-width="120" show-overflow-tooltip />
            <el-table-column label="手机号码" prop="phoneNumber" width="140" />
            <el-table-column label="邮箱地址" prop="email" min-width="180" show-overflow-tooltip />
            <el-table-column label="公司名称" prop="companyName" min-width="150" show-overflow-tooltip />
            <el-table-column label="职位" prop="position" width="120" show-overflow-tooltip />
<!--            <el-table-column label="客户标签" prop="tags" min-width="150">-->
<!--              <template slot-scope="scope">-->
<!--                <el-tag-->
<!--                  v-for="(tag, index) in getTagList(scope.row.tags)"-->
<!--                  :key="index"-->
<!--                  size="small"-->
<!--                  :type="getTagType(index)"-->
<!--                  style="margin-right: 5px;"-->
<!--                >{{ tag }}</el-tag>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column label="所属分组" prop="groupName" width="120" />
            <el-table-column label="创建时间" prop="createTime" width="160" align="center">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateCustomer(scope.row)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteCustomer(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          </div>

          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getCustomerList"
            class="pagination-container"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 客户分组对话框 -->
    <el-dialog :title="groupDialogTitle" :visible.sync="groupDialogVisible" width="500px" append-to-body>
      <el-form ref="groupForm" :model="groupForm" :rules="groupRules" label-width="80px">
        <el-form-item label="上级分组" prop="parentId">
          <treeselect
            v-model="groupForm.parentId"
            :options="parentGroupOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择上级分组"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="groupForm.groupName" placeholder="请输入分组名称" />
        </el-form-item>
        <el-form-item label="分组描述" prop="description">
          <el-input
            v-model="groupForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分组描述"
          />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="groupForm.orderNum" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGroupForm">确 定</el-button>
        <el-button @click="cancelGroupForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 客户信息对话框 -->
    <el-dialog :title="customerDialogTitle" :visible.sync="customerDialogVisible" width="600px" append-to-body>
      <el-form ref="customerForm" :model="customerForm" :rules="customerRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="customerForm.customerName" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="customerForm.phoneNumber" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="customerForm.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分组" prop="groupId">
                <treeselect
                  v-model="customerForm.groupId"
                  :options="parentGroupOptions"
                  :normalizer="normalizer"
                  :show-count="true"
                  placeholder="请选择所属分组"
                  style="width: 100%;"
                />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="customerForm.companyName" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="customerForm.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-form-item label="客户标签" prop="tags">-->
<!--          <el-input-->
<!--            v-model="customerForm.tags"-->
<!--            placeholder="请输入客户标签，多个标签用逗号分隔"-->
<!--          />-->
<!--          <div class="form-tips">-->
<!--            <i class="el-icon-info"></i>-->
<!--            <span>标签用于客户分类，便于精准营销，如：VIP客户,潜在客户等</span>-->
<!--          </div>-->
<!--        </el-form-item>-->
        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="customerForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCustomerForm">确 定</el-button>
        <el-button @click="cancelCustomerForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量分组对话框 -->
    <el-dialog title="批量分组" :visible.sync="batchGroupDialogVisible" width="400px" append-to-body>
      <el-form ref="batchGroupForm" :model="batchGroupForm" label-width="80px">
        <el-form-item label="目标分组" prop="groupId">
          <treeselect
                  v-model="batchGroupForm.groupId"
                  :options="parentGroupOptions"
                  :normalizer="normalizer"
                  :show-count="true"
                  placeholder="请选择所属分组"
                  style="width: 100%;"
                />
        </el-form-item>
        <div class="batch-info">
          <p>将 <strong>{{ selectedCustomers.length }}</strong> 个客户移动到指定分组</p>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchGroup">确 定</el-button>
        <el-button @click="batchGroupDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入客户对话框 -->
    <el-dialog title="批量导入客户" :visible.sync="importDialogVisible" width="800px" append-to-body>
      <div class="import-content">
        <div class="import-tips">
          <el-alert
            title="导入说明"
            type="info"
            :closable="false"
          >
            <template slot="default">
              <p>1. 请按照模板格式准备数据，支持Excel格式(.xlsx, .xls)</p>
              <p>2. 文件大小不能超过10MB，单次最多导入10000条记录</p>
              <p>3. 手机号码为必填字段，系统会自动去重</p>
            </template>
          </el-alert>
        </div>

        <div class="import-actions">
          <el-button type="primary" @click="downloadTemplate">
            <i class="el-icon-download"></i>
            下载导入模板
          </el-button>
        </div>

        <div class="import-upload">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx,.xls"
            action="#"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeUpload"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
          </el-upload>
        </div>

        <!-- 导入进度 -->
        <div v-if="importLoading" class="import-progress">
          <p>正在导入数据，请稍候...</p>
          <el-progress :percentage="importProgress" :text-inside="true" :stroke-width="20"></el-progress>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport" :loading="importLoading">开始导入</el-button>
        <el-button @click="importDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog title="导入结果" :visible.sync="importResultDialogVisible" width="600px" append-to-body>
      <div class="import-result">
        <!-- 统计信息 -->
        <div class="result-summary">
          <div class="summary-item">
            <div class="summary-label">总记录数</div>
            <div class="summary-value">{{ importResult.total }}</div>
          </div>
          <div class="summary-item success">
            <div class="summary-label">成功导入</div>
            <div class="summary-value">{{ importResult.success }}</div>
          </div>
          <div class="summary-item failed">
            <div class="summary-label">导入失败</div>
            <div class="summary-value">{{ importResult.failed }}</div>
          </div>
        </div>

        <!-- 错误详情 -->
        <div v-if="importResult.errors.length > 0" class="error-details">
          <h4>错误详情</h4>
          <div class="error-list">
            <div v-for="(error, index) in importResult.errors" :key="index" class="error-item">
              <i class="el-icon-warning"></i>
              <span>{{ error }}</span>
            </div>
          </div>
        </div>

        <!-- 成功提示 -->
        <div v-if="importResult.success > 0 && importResult.failed === 0" class="success-tip">
          <i class="el-icon-success"></i>
          <span>恭喜！所有数据都已成功导入</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importResultDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listContactCustomer,
  getContactCustomer,
  addContactCustomer,
  updateContactCustomer,
  delContactCustomer,
  exportContactCustomer,
  batchUpdateCustomerGroup,
  searchCustomers,
  checkPhoneUnique,
  importContactCustomer,
  downloadImportTemplate
} from "@/api/Sms/contactCustomer";
import {
  listContactGroup,
  treeSelectContactGroup,
  getContactGroup,
  addContactGroup,
  updateContactGroup,
  delContactGroup
} from "@/api/Sms/contactGroup";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as XLSX from 'xlsx';
import RightToolbar from "@/components/RightToolbar";
import {
  addSmstemlategroup,
  delSmstemlategroup,
  listSmstemlategroup,
  updateSmstemlategroup
} from "@/api/Sms/smstemlategroup";

export default {
  name: "SmsContact",
  components: { Treeselect, RightToolbar },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 选中数组
      selectedCustomers: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      // 当前选中分组
      currentGroupId: 'all',
      currentGroupName: '全部客户',
      // 分组搜索文本
      groupSearchText: '',
      // 分组树数据
      groupTreeData: [],
      groupTreeSelect: [],
      flatGroups: [],
      defaultProps: {
        children: 'children',
        label: 'groupName'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        phoneNumber: null,
        tags: null,
        groupId: null
      },
      // 分组对话框
      groupDialogVisible: false,
      groupDialogTitle: "",
      groupForm: {},
      groupRules: {
        parentId: [
          { required: true, message: "上级分组不能为空", trigger: "blur" }
        ],
        groupName: [
          { required: true, message: "分组名称不能为空", trigger: "blur" }
        ]
      },
      // 客户对话框
      customerDialogVisible: false,
      customerDialogTitle: "",
      customerForm: {},
      customerRules: {
        customerName: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "手机号码格式不正确", trigger: "blur" }
        ],
        email: [
          { type: 'email', message: "邮箱格式不正确", trigger: "blur" }
        ]
      },
      // 批量分组对话框
      batchGroupDialogVisible: false,
      batchGroupForm: {},
      // 导入对话框
      importDialogVisible: false,
      importLoading: false,
      fileList: [],

      // 导入状态和结果
      importProgress: 0,
      importResult: {
        total: 0,
        success: 0,
        failed: 0,
        errors: []
      },
      importResultDialogVisible: false
    };
  },
  created() {
    this.getGroupTree();
    this.getCustomerList();
  },
  computed: {
// 当前时间
    currentTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    // 父级分组选项
    parentGroupOptions() {
      // 添加根节点
      const rootOption = {
        id: 0,
        groupId: 0,
        groupName: '全部模板',
        children: []
      };

      // 如果有分组数据，将其作为根节点的子节点
      if (this.groupTreeData && this.groupTreeData.length > 0) {
        // 过滤掉根节点本身，只取其子节点
        const children = this.groupTreeData[0]?.children || [];
        rootOption.children = children;
      }

      return [rootOption];
    },
    systemGroups() {
      return this.flatGroups.filter(group => group.id <= 3);
    },

    customGroups() {
      return this.flatGroups.filter(group => group.id > 3);
    },
  },
  methods: {
    // treeselect 数据转换器
    normalizer(node) {
      return {
        id: node.groupId || node.id,
        label: node.groupName || node.name,
        children: node.children
      };
    },
    /** 查询客户分组树结构 */
    getGroupTree() {
      const queryParams = {
        userId: this.$store.state.user.userId
      };
      listContactGroup(queryParams).then(response => {
        if (response.code === 200) {
          // 处理返回的树数据
          this.groupTreeData = this.processTreeData(response.data || []);
          // 生成扁平化的分组列表，用于下拉选择
          this.flatGroups = this.flattenGroups(this.groupTreeData);
        } else {
          this.$message.error('获取客戶分组失败');
          // 如果获取失败，至少显示根节点
          this.groupTreeData = this.processTreeData([]);
          this.flatGroups = [];
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取客戶分组出错', error);
        this.$message.error('获取客戶分组失败');
        // 如果获取失败，至少显示根节点
        this.groupTreeData = this.processTreeData([]);
        this.flatGroups = [];
        this.loading = false;
      });
    },

    /** 查询客户列表 */
    getCustomerList() {
      this.loading = true;
      if (this.currentGroupId !== 'all') {
        this.queryParams.groupId = this.currentGroupId;
      } else {
        this.queryParams.groupId = null;
      }

      listContactCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getCustomerList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.groupId = null;
      this.currentGroupId = 'all';
      this.currentGroupName = '全部客户';
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedCustomers = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },


    /** 获取模板分组树 */
    getContactGroupTree() {
      this.loading = true;
      const queryParams = {
        userId: this.$store.state.user.userId
      };

      listContactGroup(queryParams).then(response => {
        if (response.code === 200) {
          // 处理返回的树数据
          this.groupTreeData = this.processTreeData(response.data || []);
          // 生成扁平化的分组列表，用于下拉选择
          this.flatGroups = this.flattenGroups(this.groupTreeData);
        } else {
          this.$message.error('获取模板分组失败');
          // 如果获取失败，至少显示根节点
          this.groupTreeData = this.processTreeData([]);
          this.flatGroups = [];
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取模板分组出错', error);
        this.$message.error('获取模板分组失败');
        // 如果获取失败，至少显示根节点
        this.groupTreeData = this.processTreeData([]);
        this.flatGroups = [];
        this.loading = false;
      });
    },

    // 处理树数据，添加图标等信息
    processTreeData(treeData) {
      // 确保 treeData 是数组
      if (!Array.isArray(treeData)) {
        console.warn('Tree data is not an array:', treeData);
        treeData = [];
      }

      const processNode = (node) => {
        // 确保节点有必要的属性
        const processedNode = {
          ...node,
          groupId: node.groupId || node.id,
          groupName: node.groupName || node.name,
          children: []
        };

        // 设置节点图标和类型
        if (!processedNode.parentId || processedNode.parentId === '0' || processedNode.parentId === 0) {
          processedNode.icon = 'el-icon-folder-opened';
          processedNode.type = processedNode.groupId <= 3 ? 'system' : 'user';
        } else {
          processedNode.icon = 'el-icon-folder';
          processedNode.type = 'user';
        }

        // 递归处理子节点
        if (node.children && Array.isArray(node.children) && node.children.length > 0) {
          processedNode.children = node.children.map(child => processNode(child));
        }

        return processedNode;
      };

      // 构建树形结构 - 如果后端返回的不是树形结构，则需要构建
      let processedData = [];

      if (treeData.length > 0 && treeData[0].children !== undefined) {
        // 后端返回的已经是树形结构
        processedData = treeData.map(node => processNode(node));
      } else {
        // 后端返回的是扁平结构，需要构建树形结构
        processedData = this.buildTreeFromFlat(treeData).map(node => processNode(node));
      }

      // 添加"全部模板"根节点
      const rootNodes = [{
        groupId: 0,
        id: 0,
        groupName: '全部模板',
        icon: 'el-icon-s-home',
        type: 'system',
        children: processedData
      }];

      return rootNodes;
    },

    // 扁平化分组树，用于下拉选择
    flattenGroups(groups, result = []) {
      if (!Array.isArray(groups)) {
        return result;
      }

      groups.forEach(group => {
        if (group.groupId !== 0) { // 排除"全部模板"节点
          result.push({
            id: Number(group.groupId), // Ensure it's a number
            name: group.groupName
          });
        }

        if (group.children && Array.isArray(group.children) && group.children.length > 0) {
          this.flattenGroups(group.children, result);
        }
      });

      return result;
    },
    // 从扁平数据构建树形结构
    buildTreeFromFlat(flatData) {
      if (!Array.isArray(flatData) || flatData.length === 0) {
        return [];
      }

      // 创建映射对象
      const idMap = {};
      const tree = [];

      // 第一遍遍历，创建所有节点
      flatData.forEach(item => {
        const node = {
          ...item,
          children: []
        };
        idMap[item.groupId || item.id] = node;
      });

      // 第二遍遍历，建立父子关系
      flatData.forEach(item => {
        const node = idMap[item.groupId || item.id];
        const parentId = item.parentId;

        if (parentId && parentId !== 0 && parentId !== '0' && idMap[parentId]) {
          // 有父节点，添加到父节点的children中
          idMap[parentId].children.push(node);
        } else {
          // 没有父节点或父节点是0，添加到根级
          tree.push(node);
        }
      });

      return tree;
    },

    // 处理树节点点击
    handleNodeClick(data) {
      console.log('点击节点:', data);
      if (data.groupId === 0) {
        // 点击"全部模板"，清除分组筛选
        this.currentGroupId = null;
        this.queryParams.groupId = null;
      } else {
        // 点击具体分组，设置分组ID筛选
        this.currentGroupId = data.groupId;
        this.queryParams.groupId = data.groupId;
      }

      // 重新加载模板列表
      this.getCustomerList();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 新增分组 */
    handleAddGroup(parentData) {
      this.groupForm = {
        groupId: null,
        groupName: '',
        parentId: parentData && parentData.groupId ? parseInt(parentData.groupId, 10) : 0
      };
      this.groupDialogVisible = true;
      this.groupDialogTitle = "添加客户分组";
    },

    /** 修改分组 */
    handleGroupUpdate(row) {
      // 检查groupId是否有效
      if (!row || row.groupId === undefined || row.groupId === null) {
        this.$message.error('分组ID无效，无法编辑');
        return;
      }

      // 确保groupId是数字类型
      const groupId = parseInt(row.groupId, 10);
      if (isNaN(groupId) || groupId <= 0) {
        this.$message.error('分组ID无效，无法编辑');
        return;
      }
      getContactGroup(groupId).then(response => {
        this.groupForm = {
          ...response.data,
          // 确保数值类型正确
          groupId: parseInt(response.data.groupId, 10),
          parentId: parseInt(response.data.parentId, 10) || 0
        };
        this.groupDialogVisible = true;
        this.groupDialogTitle = "修改客户分组";
      });
    },

    /** 删除分组 */
    handleGroupDelete(node, data) {
      // 检查groupId是否有效
      if (!data || data.groupId === undefined || data.groupId === null) {
        this.$message.error('分组ID无效，无法删除');
        return;
      }

      // 确保groupId是数字类型
      const groupId = parseInt(data.groupId, 10);
      if (isNaN(groupId) || groupId <= 0) {
        this.$message.error('分组ID无效，无法删除');
        return;
      }

      this.$confirm(`确定要删除分组"${data.groupName}"吗？删除后分组内的客户将移至默认分组。`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          delContactGroup(groupId).then(response => {
            if (response.code === 200) {
              this.$message.success('删除分组成功');
              // 如果当前选中的是被删除的分组，切换到全部模板
              if (this.currentGroupId === groupId) {
                this.currentGroupId = null;
                this.queryParams.groupId = null;
                this.getCustomerList(); // 重新加载模板列表
              }
              // 刷新分组树
              this.getGroupTree();
            } else {
              this.$message.error('删除分组失败: ' + (response.msg || '未知错误'));
            }
          }).catch(error => {
            console.error('删除分组出错', error);
            this.$message.error('删除分组失败: ' + (error.message || '未知错误'));
          });
      }).catch(() => {
        // 取消删除操作
      });
    },

    /** 提交分组表单 */
    submitGroupForm() {
      this.$refs["groupForm"].validate(valid => {
        if (valid) {
          const data = {
            groupName: this.groupForm.groupName,
            parentId: parseInt(this.groupForm.parentId, 10) || 0,
            userId: this.$store.state.user.userId
          };

          // 判断是新增还是编辑
          if (this.groupForm.groupId) {
            // 编辑模式
            data.groupId = parseInt(this.groupForm.groupId, 10);

            updateContactGroup(data).then(response => {
              if (response.code === 200) {
                this.$message.success('修改分组成功');
                this.groupDialogVisible = false;
                this.getContactGroupTree(); // 刷新分组树
              } else {
                this.$message.error('修改分组失败: ' + (response.msg || '未知错误'));
              }
            }).catch(error => {
              console.error('修改分组出错', error);
              this.$message.error('修改分组失败: ' + (error.message || '未知错误'));
            });
          } else {
            // 新增模式
            addContactGroup(data).then(response => {
              if (response.code === 200) {
                this.$message.success('添加分组成功');
                this.groupDialogVisible = false;
                this.getContactGroupTree(); // 刷新分组树
              } else {
                this.$message.error('添加分组失败: ' + (response.msg || '未知错误'));
              }
            }).catch(error => {
              console.error('添加分组出错', error);
              this.$message.error('添加分组失败: ' + (error.message || '未知错误'));
            });
          }
        }
      });
    },

    /** 取消分组按钮 */
    cancelGroupForm() {
      this.groupDialogVisible = false;
      this.resetGroupForm();
    },

    /** 表单重置 */
    resetGroupForm() {
      this.groupForm = {
        groupId: null,
        parentId: 0,
        groupName: null,
        description: null,
        orderNum: 0
      };
      this.resetForm("groupForm");
    },

    /** 新增客户按钮操作 */
    handleAddCustomer() {
      this.resetCustomerForm();
      this.customerDialogVisible = true;
      this.customerDialogTitle = "添加客户";
      // 设置默认分组
      if (this.currentGroupId !== 'all') {
        this.customerForm.groupId = this.currentGroupId;
      }
    },

    /** 修改客户按钮操作 */
    handleUpdateCustomer(row) {
      this.resetCustomerForm();
      const customerId = row.customerId;
      getContactCustomer(customerId).then(response => {
        this.customerForm = response.data;
        this.customerDialogVisible = true;
        this.customerDialogTitle = "修改客户";
      });
    },

    /** 删除客户按钮操作 */
    handleDeleteCustomer(row) {
      const customerIds = row.customerId;
      this.$modal.confirm('是否确认删除客户"' + row.customerName + '"？').then(function() {
        return delContactCustomer(customerIds);
      }).then(() => {
        this.getCustomerList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 提交客户表单 */
    submitCustomerForm() {
      this.$refs["customerForm"].validate(valid => {
        if (valid) {
          if (this.customerForm.customerId != null) {
            updateContactCustomer(this.customerForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.customerDialogVisible = false;
              this.getCustomerList();
            });
          } else {
            addContactCustomer(this.customerForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.customerDialogVisible = false;
              this.getCustomerList();
            });
          }
        }
      });
    },

    /** 取消客户按钮 */
    cancelCustomerForm() {
      this.customerDialogVisible = false;
      this.resetCustomerForm();
    },

    /** 表单重置 */
    resetCustomerForm() {
      this.customerForm = {
        customerId: null,
        customerName: null,
        phoneNumber: null,
        email: null,
        companyName: null,
        position: null,
        tags: null,
        groupId: null,
        remark: null
      };
      this.resetForm("customerForm");
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('Sms/contactCustomer/export', {
        ...this.queryParams
      }, `客户信息_${new Date().getTime()}.xlsx`)
    },

    /** 获取标签列表 */
    getTagList(tags) {
      if (!tags) return [];
      return tags.split(',').filter(tag => tag.trim());
    },

    /** 获取标签类型 */
    getTagType(index) {
      const types = ['', 'success', 'info', 'warning', 'danger'];
      return types[index % types.length];
    },

    /** 发送消息 */
    handleSendMessage(row) {
      this.$router.push({
        path: '/smstask/massMessaging',
        query: {
          customerIds: row.customerId,
          customerNames: row.customerName,
          phoneNumbers: row.phoneNumber
        }
      });
    },

    /** 批量分组 */
    handleBatchGroup() {
      this.batchGroupForm = {
        groupId: null,
        tagIds: this.selectedCustomers.map(item => item.customerId)
      };
      this.batchGroupDialogVisible = true;
    },

    /** 提交批量分组 */
    submitBatchGroup() {
      if (!this.batchGroupForm.groupId) {
        this.$modal.msgError("请选择目标分组");
        return;
      }

      batchUpdateCustomerGroup(this.batchGroupForm).then(response => {
        this.$modal.msgSuccess("批量分组成功");
        this.batchGroupDialogVisible = false;
        this.getCustomerList();
        this.selectedCustomers = [];
      });
    },

    /** 批量删除 */
    handleBatchDelete() {
      const customerIds = this.selectedCustomers.map(item => item.customerId);
      this.$modal.confirm('是否确认删除选中的' + customerIds.length + '个客户？').then(function() {
        return delContactCustomer(customerIds);
      }).then(() => {
        this.getCustomerList();
        this.selectedCustomers = [];
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导入客户 */
    handleImportCustomer() {
      this.importDialogVisible = true;
      this.fileList = [];
    },

    /** 下载导入模板 */
    downloadTemplate() {
      try {
        // 创建工作簿
        const wb = XLSX.utils.book_new();

        // 创建工作表数据 - 根据截图的Excel结构
        const data = [
          ['客户编码', '客户姓名', '手机号码', '邮箱地址', '公司名称', '职位', '地址', '生日', '备注', '客户类型', '客户来源', '联系状态', '状态'],
          ['C001', '张三', '18888888888', 'zhangsan@example.com', '示例公司', '经理', '北京市朝阳区', '1990-01-01', '重要客户', 'VIP', '线上推广', '已联系', '激活'],
          ['C002', '李四', '13999999999', 'lisi@example.com', '测试企业', '主管', '上海市浦东新区', '1985-05-15', '潜在客户', '普通', '朋友介绍', '待联系', '激活'],
          ['C003', '王五', '15666666666', 'wangwu@example.com', 'ABC科技', '总监', '深圳市南山区', '1988-12-20', '合作伙伴', 'VIP', '展会获取', '已联系', '激活']
        ];

        // 将数据转换为工作表
        const ws = XLSX.utils.aoa_to_sheet(data);

        // 设置列宽
        ws['!cols'] = [
          { wch: 12 }, // 客户编码
          { wch: 15 }, // 客户姓名
          { wch: 15 }, // 手机号码
          { wch: 25 }, // 邮箱地址
          { wch: 20 }, // 公司名称
          { wch: 12 }, // 职位
          { wch: 25 }, // 地址
          { wch: 15 }, // 生日
          { wch: 20 }, // 备注
          { wch: 12 }, // 客户类型
          { wch: 15 }, // 客户来源
          { wch: 12 }, // 联系状态
          { wch: 10 }  // 状态
        ];

        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '客户信息导入模板');

        // 将工作簿写入文件并触发下载
        XLSX.writeFile(wb, '客户信息导入模板.xlsx');

        this.$message.success('模板下载成功');
      } catch (error) {
        console.error('导出Excel出错:', error);
        this.$message.error('导出Excel出错，请稍后再试');
      }
    },

    /** 文件上传改变 */
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },

    /** 文件移除 */
    handleFileRemove() {
      this.fileList = [];
    },

    /** 上传前检查 */
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                     file.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$modal.msgError('上传文件只能是 Excel 格式!');
        return false;
      }
      if (!isLt10M) {
        this.$modal.msgError('上传文件大小不能超过 10MB!');
        return false;
      }
      return true;
    },

    /** 提交导入 */
    submitImport() {
      if (this.fileList.length === 0) {
        this.$modal.msgError("请选择要导入的文件");
        return;
      }

      this.importLoading = true;

      // 重置导入结果
      this.importResult = {
        total: 0,
        success: 0,
        failed: 0,
        errors: []
      };

      const file = this.fileList[0].raw;

      try {
        const reader = new FileReader();

        reader.onload = (e) => {
          try {
            // 使用 xlsx 库解析 Excel 文件
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });

            // 读取第一个工作表
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];

            // 将工作表转换为JSON
            const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

            if (rows.length <= 1) {
              this.importLoading = false;
              this.$modal.msgWarning('文件内容为空或只有表头，请检查文件格式');
              return;
            }

            const headers = rows[0]; // 第一行作为表头
            console.log("表头行:", headers);

            // 处理数据行
            const importData = [];
            const errors = [];

            for (let i = 1; i < rows.length; i++) {
              const row = rows[i];
              if (!row || row.length === 0) continue;

              try {
                // 根据Excel结构映射数据
                const customerData = {
                  customerCode: this.getCellValue(row[0]) || '', // 客户编码
                  customerName: this.getCellValue(row[1]) || '', // 客户姓名
                  phoneNumber: this.getCellValue(row[2]) || '', // 手机号码
                  email: this.getCellValue(row[3]) || '', // 邮箱地址
                  companyName: this.getCellValue(row[4]) || '', // 公司名称
                  position: this.getCellValue(row[5]) || '', // 职位
                  address: this.getCellValue(row[6]) || '', // 地址
                  birthday: this.getCellValue(row[7]) || '', // 生日
                  remark: this.getCellValue(row[8]) || '', // 备注
                  customerType: this.getCellValue(row[9]) || '', // 客户类型
                  customerSource: this.getCellValue(row[10]) || '', // 客户来源
                  contactStatus: this.getCellValue(row[11]) || '', // 联系状态
                  status: this.getCellValue(row[12]) || '', // 状态
                  groupId: this.currentGroupId === 'all' ? null : this.currentGroupId, // 当前选中的分组
                  userId: this.$store.state.user.userId
                };

                // 验证必填字段
                if (!customerData.customerName) {
                  errors.push(`第 ${i + 1} 行：客户姓名不能为空`);
                  continue;
                }

                if (!customerData.phoneNumber) {
                  errors.push(`第 ${i + 1} 行：手机号码不能为空`);
                  continue;
                }

                // 验证手机号格式
                const phoneRegex = /^1[3-9]\d{9}$/;
                if (!phoneRegex.test(customerData.phoneNumber)) {
                  errors.push(`第 ${i + 1} 行：手机号码格式不正确 - ${customerData.phoneNumber}`);
                  continue;
                }

                // 验证邮箱格式（如果填写了邮箱）
                if (customerData.email) {
                  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                  if (!emailRegex.test(customerData.email)) {
                    errors.push(`第 ${i + 1} 行：邮箱格式不正确 - ${customerData.email}`);
                    continue;
                  }
                }

                importData.push(customerData);
              } catch (error) {
                console.error(`处理第 ${i + 1} 行数据出错:`, error);
                errors.push(`第 ${i + 1} 行：数据处理出错 - ${error.message}`);
              }
            }

            this.importResult.total = rows.length - 1; // 排除表头行
            this.importResult.errors = errors;

            if (importData.length === 0) {
              this.importLoading = false;
              this.$modal.msgWarning('没有有效的数据可以导入，请检查文件内容');
              this.importResult.failed = this.importResult.total;
              this.importResultDialogVisible = true;
              return;
            }

            // 批量导入数据
            this.batchImportCustomers(importData);

          } catch (error) {
            console.error('解析Excel出错:', error);
            this.importLoading = false;
            this.$modal.msgError('解析Excel文件出错，请检查文件格式');
          }
        };

        reader.onerror = () => {
          this.importLoading = false;
          this.$modal.msgError('读取文件失败');
        };

        // 以二进制格式读取文件
        reader.readAsArrayBuffer(file);
      } catch (error) {
        console.error('文件处理错误:', error);
        this.importLoading = false;
        this.$modal.msgError('文件处理错误，请稍后再试');
      }
    },

    /** 获取单元格值 */
    getCellValue(cell) {
      if (cell === null || cell === undefined) return '';
      return String(cell).trim();
    },

    /** 批量导入客户数据 */
    async batchImportCustomers(importData) {
      try {
        let successCount = 0;
        let failedCount = 0;

        // 分批处理，每次处理100条记录
        const batchSize = 100;
        for (let i = 0; i < importData.length; i += batchSize) {
          const batch = importData.slice(i, i + batchSize);

          try {
            // 逐个添加客户，以便更好地处理错误
            for (const customerData of batch) {
              try {
                const response = await addContactCustomer(customerData);
                if (response.code === 200) {
                  successCount++;
                } else {
                  failedCount++;
                  this.importResult.errors.push(`客户 ${customerData.customerName} 导入失败: ${response.msg}`);
                }
              } catch (error) {
                failedCount++;
                this.importResult.errors.push(`客户 ${customerData.customerName} 导入失败: ${error.message}`);
              }
            }
          } catch (error) {
            console.error('批次导入出错:', error);
            failedCount += batch.length;
            this.importResult.errors.push(`批次导入失败: ${error.message}`);
          }

          // 更新进度
          this.importProgress = Math.round(((i + batch.length) / importData.length) * 100);
        }

        this.importResult.success = successCount;
        this.importResult.failed = failedCount;

        this.importLoading = false;
        this.importDialogVisible = false;

        // 显示导入结果
        if (successCount > 0) {
          this.$modal.msgSuccess(`导入完成！成功导入 ${successCount} 条记录，失败 ${failedCount} 条记录。`);
          // 刷新客户列表
          this.getCustomerList();
        } else {
          this.$modal.msgError('导入失败，没有成功导入任何记录');
        }

        // 显示详细结果
        this.importResultDialogVisible = true;

      } catch (error) {
        console.error('导入过程出错:', error);
        this.importLoading = false;
        this.$modal.msgError('导入过程出错，请稍后再试');
      }
    }
  }
};
</script>

<style scoped>
.sms-contact-container {
  padding: 0px;
  background-color: #f8f9fa;
  height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
}

.sms-contact-container > .el-row {
  flex-grow: 1;
  display: flex;
  margin: 0 !important;
}

.sms-contact-container > .el-row > .el-col {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 !important;
}

.sms-contact-container .el-card {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  margin: 0;
  border-radius: 0;
}

.sms-contact-container .el-card >>> .el-card__body {
  flex-grow: 1;
  overflow: hidden;
  padding: 20px;
  display: flex;
  flex-direction: column;
}


/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-title i {
  font-size: 20px;
  color: #409eff;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 搜索工具栏样式 */
.search-toolbar {
  margin-bottom: 16px;
  flex-shrink: 0;
}

/* 表格容器样式 */
.table-container {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  max-height: calc(100vh - 360px);
  min-height: 300px;
}

.el-table {
  margin-bottom: 0;
}

.pagination-container {
  text-align: right;
  margin-top: 0;
  padding: 0px 0;
  flex-shrink: 0;
  border-top: 1px solid #ebeef5;
  background-color: #fff;
}

/* 列布局样式 */
.group-tree-col {
  width: 300px !important;
  min-width: 300px;
  max-width: 300px;
  flex: 0 0 300px;
  padding-right: 0 !important;
}

.group-tree-card {
  width: 100%;
  margin-right: 0;
  border-right: 1px solid #ebeef5;
  border-radius: 0;
}

.customer-list-col {
  flex: 1 !important;
  width: calc(100% - 300px) !important;
  max-width: none !important;
  padding-left: 0 !important;
}

.customer-list-card {
  width: 100%;
  border-radius: 0;
  border-left: none;
}
.add-group-btn {
  color: #3b82f6;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  border: 1px solid #dbeafe;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  transition: all 0.3s ease;
  font-weight: 500;
  display: none;
  align-items: center;
  gap: 4px;
  opacity: 0;
  transition: all 0.3s ease;
}

.add-group-btn:hover {
  color: #ffffff;
  background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
  border-color: #3b82f6;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.add-group-btn i {
  font-size: 14px;
  margin-right: 6px;
}


/* 对话框样式 */
.form-tips {
  margin-top: 4px;
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.batch-info {
  text-align: center;
  color: #606266;
  background: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  margin-top: 12px;
  font-size: 15px;
}

/* 导入对话框样式 */
.import-content {
  padding: 8px 0;
}

.import-tips {
  margin-bottom: 20px;
}

.import-tips .el-alert {
  font-size: 14px;
}

.import-actions {
  margin-bottom: 20px;
  text-align: center;
}

.import-actions .el-button {
  font-size: 14px;
  padding: 10px 20px;
}

.import-upload {
  margin-bottom: 20px;
}

.import-upload .el-upload__text {
  font-size: 14px;
}

.import-upload .el-upload__tip {
  font-size: 13px;
}





/* 统一的el-tree样式 */
.group-tree-card .el-tree {
  background-color: transparent;
}

.group-tree-card .el-tree-node {
  margin-bottom: 4px;
}

.group-tree-card >>> .el-tree-node__content {
  height: 36px !important;
  line-height: 36px !important;
  min-height: 36px !important;
  padding: 0 10px 0 0 !important;
}

.group-tree-card .el-tree-node__expand-icon {
  padding: 6px;
}

.group-tree-card .el-tree-node__label {
  font-size: 14px;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 0px;
  font-size: 14px;
  height: 36px;
  line-height: 36px;
}

.node-label {
  display: flex;
  align-items: center;
}

.tree-icon {
  margin-right: 8px;
  font-size: 16px;
}

.node-actions {
  display: none;
  gap: 4px;
}

.custom-tree-node:hover .node-actions {
  display: flex;
}

.action-icon {
  margin-left: 8px;
  font-size: 14px;
  color: #9ca3af;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.action-icon:hover {
  color: #ffffff;
  background: #3b82f6;
}



/* Treeselect 组件样式 - 与Element UI标准控件一致 */
::v-deep .vue-treeselect {
  font-size: 14px;
}

::v-deep .vue-treeselect__control {
  height: 40px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background: #ffffff;
  font-family: inherit;
}

::v-deep .vue-treeselect__control:hover {
  border-color: #c0c4cc;
}

::v-deep .vue-treeselect__control--is-focused {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  line-height: 38px;
  color: #606266;
  font-size: 14px;
}

::v-deep .vue-treeselect__menu {
  border: 1px solid #E4E7ED;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background: #ffffff;
  z-index: 9999;
  max-width: 300px;
  min-width: 220px;
}

::v-deep .vue-treeselect__list {
  max-height: 280px;
  overflow-y: auto;
  padding: 6px 0;
}

/* 统一选项样式 - 与Element UI Select保持一致 */
::v-deep .vue-treeselect__option {
  padding: 0;
  margin: 0;
  border-radius: 0;
  cursor: pointer;
  transition: background-color 0.3s ease;
  display: flex;
  align-items: center;
  min-height: 36px;
  font-size: 14px;
  color: #606266;
}

::v-deep .vue-treeselect__option:hover {
  background-color: #f5f7fa;
}

::v-deep .vue-treeselect__option--selected {
  background-color: #f5f7fa;
  color: #409EFF;
  font-weight: 500;
}

::v-deep .vue-treeselect__option--selected:hover {
  background-color: #f5f7fa;
}

/* 展开箭头容器 */
::v-deep .vue-treeselect__option-arrow-container {
  width: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

/* 展开箭头样式 - 使用标准颜色 */
::v-deep .vue-treeselect__option-arrow {
  border-left: 6px solid #C0C4CC;
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent;
  transition: all 0.3s ease;
}

::v-deep .vue-treeselect__option--expanded .vue-treeselect__option-arrow {
  transform: rotate(90deg);
  border-left-color: #909399;
}

::v-deep .vue-treeselect__option:hover .vue-treeselect__option-arrow {
  border-left-color: #909399;
}

/* 标签容器统一对齐 */
::v-deep .vue-treeselect__label-container {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 0 12px;
  min-height: 36px;
}

::v-deep .vue-treeselect__label {
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
  flex: 1;
  font-weight: 400;
}

::v-deep .vue-treeselect__option:hover .vue-treeselect__label {
  color: #606266;
}

::v-deep .vue-treeselect__option--selected .vue-treeselect__label {
  color: #409EFF;
  font-weight: 500;
}

/* 层级缩进 - 与Element UI Tree保持一致 */
::v-deep .vue-treeselect__indent-level-1 .vue-treeselect__label-container {
  padding-left: 36px;
}

::v-deep .vue-treeselect__indent-level-2 .vue-treeselect__label-container {
  padding-left: 56px;
}

::v-deep .vue-treeselect__indent-level-3 .vue-treeselect__label-container {
  padding-left: 76px;
}

::v-deep .vue-treeselect__indent-level-4 .vue-treeselect__label-container {
  padding-left: 96px;
}

/* 根节点样式 - 简化为标准样式 */
::v-deep .vue-treeselect__option[data-id="0"] {
  background: transparent;
  border: none;
  border-radius: 0;
  margin: 0;
}

::v-deep .vue-treeselect__option[data-id="0"] .vue-treeselect__label-container {
  padding: 0 12px;
}

::v-deep .vue-treeselect__option[data-id="0"] .vue-treeselect__label {
  color: #606266;
  font-weight: 600;
  font-size: 15px;
}

::v-deep .vue-treeselect__option[data-id="0"]:hover {
  background: #f5f7fa;
  border: none;
}

::v-deep .vue-treeselect__option[data-id="0"]:hover .vue-treeselect__label {
  color: #606266;
}

::v-deep .vue-treeselect__option[data-id="0"]--selected {
  background: #f5f7fa;
  border: none;
}

::v-deep .vue-treeselect__option[data-id="0"]--selected .vue-treeselect__label {
  color: #409EFF;
  font-weight: 600;
}

/* 计数标签 - 使用Element UI标准样式 */
::v-deep .vue-treeselect__count {
  background: #f4f4f5;
  color: #909399;
  border-radius: 3px;
  padding: 2px 6px;
  font-size: 12px;
  margin-left: 8px;
  font-weight: 400;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 16px;
  height: 18px;
  line-height: 14px;
  flex-shrink: 0;
}

::v-deep .vue-treeselect__option:hover .vue-treeselect__count {
  background: #e4e7ed;
  color: #909399;
}

::v-deep .vue-treeselect__option--selected .vue-treeselect__count {
  background: #ecf5ff;
  color: #409EFF;
}

/* 下拉箭头 - 与Element UI一致 */
::v-deep .vue-treeselect__arrow-container {
  height: 38px;
  width: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep .vue-treeselect__arrow {
  color: #C0C4CC;
  transition: color 0.3s ease;
  font-size: 14px;
}

::v-deep .vue-treeselect__control:hover .vue-treeselect__arrow {
  color: #909399;
}

::v-deep .vue-treeselect__control--is-focused .vue-treeselect__arrow {
  color: #409EFF;
}

/* 清除按钮 */
::v-deep .vue-treeselect__x-container {
  width: 32px;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep .vue-treeselect__x {
  color: #C0C4CC;
  transition: color 0.3s ease;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

::v-deep .vue-treeselect__x:hover {
  color: #909399;
  background: rgba(144, 147, 153, 0.1);
}

/* 空状态 */
::v-deep .vue-treeselect__no-options {
  padding: 12px 16px;
  text-align: center;
  color: #C0C4CC;
  font-size: 14px;
}

/* 加载状态 */
::v-deep .vue-treeselect__loading {
  padding: 12px 16px;
  text-align: center;
  color: #C0C4CC;
  font-size: 14px;
}

/* 导入进度 */
.import-progress {
  margin-top: 20px;
  text-align: center;
}

.import-progress p {
  margin-bottom: 10px;
  font-size: 14px;
}

.import-progress .el-progress {
  width: 100%;
}

/* 导入结果样式 */
.import-result {
  padding: 10px 0;
}

.result-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.summary-item {
  text-align: center;
  flex: 1;
}

.summary-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.summary-item.success .summary-value {
  color: #67c23a;
}

.summary-item.failed .summary-value {
  color: #f56c6c;
}

.error-details h4 {
  color: #f56c6c;
  margin-bottom: 15px;
  font-size: 16px;
}

.error-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fff;
}

.error-item {
  padding: 10px 15px;
  border-bottom: 1px solid #f5f7fa;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #f56c6c;
}

.error-item:last-child {
  border-bottom: none;
}

.error-item i {
  margin-right: 8px;
  font-size: 16px;
}

.success-tip {
  text-align: center;
  padding: 20px;
  background: #f0f9ff;
  border: 1px solid #e1f5fe;
  border-radius: 8px;
  color: #67c23a;
  font-size: 16px;
}

.success-tip i {
  margin-right: 8px;
  font-size: 18px;
}
</style>
